﻿/**
 * Created by Administrator on 2015/5/27.
 */


var wxInterface = {};
wxInterface.config = {}//配置
wxInterface.shareData = {}//分享
wxInterface.locationData = {}//地理位置
wxInterface.payInfo = {}//支付
wxInterface.photoList = {}//预览图
wxInterface.photo = {}//高清图像
function timestamp() {
    return (new Date()).valueOf();
}

/*ajax获取配置信息JSON*/
wxInterface.getAjaxAndConfig = function () {
    /*    $.ajax({
     url: configInfo.url + '/oa/app/weixin/sign',
     type: 'post',
     data: {'url': window.location.href.split('#')[0]},
     success: function (data) {
     wxInterface.splitConfig(data);
     //wxInterface.getLocation();//先获取地理位置
     },
     error: function () {
     alert('网络忙！');
     }
     })老版本微信支付*/

    var isurl = window.location.href.split('#')[0].replace(/&/g, '||');
    var orderid = wxInterface.split_url('id');
    var jsondata = 'body={"service":"wx","method":"getSign","sn":"' + timestamp() + '","token":"' + localStorage.getItem('token') + '","version":"2.0","channel":"WX","params":{"url":"' + isurl + '","orderId":"' + orderid + '"}}';
    //alert(jsondata);

    $.ajax({
        url: configInfo.url,
        type: 'post',
        async: false,
        dataType: 'json',
        data: jsondata,
        success: function (e) {
            //alert(e.success);
            console.log(e);
            if (e && e.success) {
                wxInterface.splitConfig(e.entity);
            } else {
                alert('错误原因:' + e.entity.reason);
            }
        },
        error: function () {
            alert('网络忙！');
        }
    })

}

/*拼接 wx.config 参数信息*/
wxInterface.splitConfig = function (data) {
    var jsObjData = data;
    //alert(jsObjData.nonce_str);
    this.config.debug = true;
    this.config.appId = jsObjData.appId;// 'wx22d352797b1b6b96';// ;
    this.config.timestamp = jsObjData.timestamp;
    this.config.nonceStr = jsObjData.nonce_str;
    this.config.signature = jsObjData.signature;
    this.config.jsApiList = eval("(" + jsObjData.jsApiList + ")");

    this.checkConfig(this.config);
}

/*通过config接口注入权限验证配置*/
wxInterface.checkConfig = function (obj) {
    //wx.config(obj);
    wx.config({
        debug: false,
        appId: obj.appId,
        timestamp: obj.timestamp,
        nonceStr: obj.nonceStr,
        signature: obj.signature,
        jsApiList: ["onMenuShareTimeline", "onMenuShareAppMessage", "onMenuShareQQ", "onMenuShareWeibo", "openLocation", "getLocation", "chooseWXPay", "previewImage"]//obj.jsApiList
    });
}

/*wx.error(function (res) {
 // config信息验证失败会执行error函数，如签名过期导致验证失败
 //alert(res.errMsg);
 alert('^_^ 哪里出错了！');
 //alert(res);
 });*/


//1.判断当前版本是否支持指定 JS 接口，支持批量判断
//wxInterface.checkJsApi = function (obj) {
/*wx.ready(function () {
 wx.checkJsApi({
 jsApiList: [
 'onMenuShareAppMessage',
 'onMenuShareTimeline',
 'onMenuShareQQ',
 'onMenuShareWeibo',
 'openLocation',
 'getLocation',
 'chooseWXPay'
 ],
 success: function (res) {
 alert(JSON.stringify(res));
 }
 });
 })*/
//}

//2.分享给朋友
wxInterface.shareToFriend = function () {
    wx.onMenuShareAppMessage({
        title: wxInterface.shareData.title,//'互联网之子',
        desc: wxInterface.shareData.desc,//'在长大的过程中，我才慢慢发现，我身边的所有事，别人跟我说的所有事，那些所谓本来如此，注定如此的事，它们其实没有非得如此，事情是可以改变的。更重要的是，有些事既然错了，那就该做出改变。',
        link: wxInterface.shareData.link,//'http://movie.douban.com/subject/25785114/',
        imgUrl: wxInterface.shareData.imgUrl,//'http://demo.open.weixin.qq.com/jssdk/images/p2166127561.jpg',
        trigger: function (res) {
            // 不要尝试在trigger中使用ajax异步请求修改本次分享的内容，因为客户端分享操作是一个同步操作，这时候使用ajax的回包会还没有返回
            alert('用户点击发送给朋友');
        },
        success: function (res) {
            alert('已分享');
        },
        cancel: function (res) {
            alert('已取消');
        },
        fail: function (res) {
            alert(JSON.stringify(res));
        }
    });
}

//3.分享到朋友圈
wxInterface.shareToFriendZone = function () {
    wx.onMenuShareTimeline({
        title: wxInterface.shareData.title,//'互联网之子',
        link: wxInterface.shareData.link,//'http://movie.douban.com/subject/25785114/',
        imgUrl: wxInterface.shareData.imgUrl,//'http://demo.open.weixin.qq.com/jssdk/images/p2166127561.jpg',
        trigger: function (res) {
            // 不要尝试在trigger中使用ajax异步请求修改本次分享的内容，因为客户端分享操作是一个同步操作，这时候使用ajax的回包会还没有返回
            alert('用户点击分享到朋友圈');
        },
        success: function (res) {
            alert('已分享');
        },
        cancel: function (res) {
            alert('已取消');
        },
        fail: function (res) {
            alert(JSON.stringify(res));
        }
    });
}

//4.分享到QQ
wxInterface.sharetoQQ = function () {
    wx.onMenuShareQQ({
        title: wxInterface.shareData.title,//'互联网之子',
        desc: wxInterface.shareData.desc,//'在长大的过程中，我才慢慢发现，我身边的所有事，别人跟我说的所有事，那些所谓本来如此，注定如此的事，它们其实没有非得如此，事情是可以改变的。更重要的是，有些事既然错了，那就该做出改变。',
        link: wxInterface.shareData.link,//'http://movie.douban.com/subject/25785114/',
        imgUrl: wxInterface.shareData.imgUrl,//'http://img3.douban.com/view/movie_poster_cover/spst/public/p2166127561.jpg',
        trigger: function (res) {
            alert('用户点击分享到QQ');
        },
        complete: function (res) {
            alert(JSON.stringify(res));
        },
        success: function (res) {
            alert('已分享');
        },
        cancel: function (res) {
            alert('已取消');
        },
        fail: function (res) {
            alert(JSON.stringify(res));
        }
    });
}

//5.分享到微博
wxInterface.shareToWeibo = function () {
    wx.onMenuShareWeibo({
        title: wxInterface.shareData.title,//'互联网之子',
        desc: wxInterface.shareData.desc,//'在长大的过程中，我才慢慢发现，我身边的所有事，别人跟我说的所有事，那些所谓本来如此，注定如此的事，它们其实没有非得如此，事情是可以改变的。更重要的是，有些事既然错了，那就该做出改变。',
        link: wxInterface.shareData.link,//'http://movie.douban.com/subject/25785114/',
        imgUrl: wxInterface.shareData.imgUrl,//'http://img3.douban.com/view/movie_poster_cover/spst/public/p2166127561.jpg',
        trigger: function (res) {
            alert('用户点击分享到微博');
        },
        complete: function (res) {
            alert(JSON.stringify(res));
        },
        success: function (res) {
            alert('已分享');
        },
        cancel: function (res) {
            alert('已取消');
        },
        fail: function (res) {
            alert(JSON.stringify(res));
        }
    });
}

//6.查看地理位置
wxInterface.openLocation = function () {
    wxInterface.getLocation();//先获取地理位置
    wx.openLocation({
        latitude: wxInterface.locationData.latitude,
        longitude: wxInterface.locationData.longitude,
        name: 'name',
        address: 'address',
        scale: 14,
        infoUrl: 'http://weixin.qq.com'
    });
}

//7.获取当前地理位置
wxInterface.getLocation = function () {
    this.locationData = {};//先清空
    wx.getLocation({
        success: function (res) {
            //alert(JSON.stringify(res));
            wxInterface.locationData.longitude = res.longitude;// 经度，浮点数，范围为180 ~ -180。
            wxInterface.locationData.latitude = res.latitude;// 纬度，浮点数，范围为90 ~ -90
            wxInterface.locationData.accuracy = res.accuracy;// 位置精度
            wxInterface.locationData.speed = res.speed;// 速度，以米/每秒计
            window.localStorage.setItem('longitude', res.longitude);
            window.localStorage.setItem('latitude', res.latitude);
            window.localStorage.setItem('accuracy', res.accuracy);
            window.localStorage.setItem('speed', res.speed);
        },
        cancel: function (res) {
            alert('用户拒绝授权获取地理位置！');
            return false;
        }
    });
}

wxInterface.split_url = function (parame) {
    var url = window.location.href;
    var param = url.substring(url.indexOf(parame + "=") + (parame.length + 1), url.length);
    var id = param.split("&")[0];
    return id;
}

//8.微信支付接口,发起一个支付请求
wxInterface.chooseWXPay = function (orderId, couponId, subject, callbackurl) {
    // 注意：此 Demo 使用 2.7 版本支付接口实现，建议使用此接口时参考微信支付相关最新文档。
    /*var token = window.localStorage.getItem('token');
     token = 'bcd60f0af34942f1876ab9eb55c29942';
     if (!token) {
     alert('未检测到您的登录状态,请先登录！');
     window.location.href = 'login.html';
     return;
     }*/

    /*$.ajax({
     type: 'post',
     url: configInfo.url + '/oa/app/tenpay/platformPrepay',
     cache: false,
     async: false,
     data: {
     'orderId': orderId,
     'tradeType': 'JSAPI',
     'token': token,
     'code': wxInterface.split_url('code'),
     'couponId': couponId,
     'subject': subject
     },
     success: function (data) {
     wxInterface.splitWXPayInfo(data, callbackurl);
     },
     error: function () {
     alert('网络忙！');
     return false;
     }
     });*/

    /*$.ajax({//取openid
     url: configInfo.url,
     type: 'post',
     async: false,
     dataType: 'json',
     data: 'body={"service":"wx","method":"getOpenId","sn":"' + timestamp() + '","token":"' + configInfo.token + '","version":"2.0","channel":"WX","params":{"code":"' + wxInterface.split_url('code') + '"}}',
     success: function (e) {
     console.log(e);

     alert(e.success + '这是openid获取状态');
     alert(e.entity.openId + '这是openid');

     }, error: function () {
     alert('网络忙！');
     return false;
     }
     })*/


    var jsondata = 'body={"service":"wx","method":"prePay","sn":"' + timestamp() + '","token":"' + localStorage.getItem('token') + '","version":"2.0","channel":"WX","params":{"orderId":"' + orderId + '","couponId":"' + couponId + '","subject":"' + subject + '","code":"' + wxInterface.split_url('code') + '"}}';
    //alert(jsondata);
    //alert(wxInterface.split_url('code') + '   这是code');

    $.ajax({
        url: configInfo.url,
        type: 'post',
        async: false,
        dataType: 'json',
        data: jsondata,
        success: function (e) {
            //alert(e.success + '这是prePay返回');
            console.log(e);
            if (e.success) {
                wxInterface.splitWXPayInfo(e, callbackurl);
            } else {
                alert('错误原因：' + e.entity.reason);
            }
        }, error: function () {
            alert('网络忙！');
            return false;
        }
    })
}

wxInterface.splitWXPayInfo = function (data, callbackurl) {
    this.payInfo = {};//先清空
    if (data) {
        var objPayInfo = data;

        //alert(objPayInfo.success);

        this.payInfo.result = objPayInfo.success;
        this.payInfo.prepay_id = objPayInfo.entity.prepay_id;
        this.payInfo.sign = objPayInfo.entity.sign;
        this.payInfo.timestamp = objPayInfo.entity.timestamp;
        this.payInfo.nonceStr = objPayInfo.entity.noncestr;
        this.payInfo.reason = objPayInfo.entity.reason;

        if (this.payInfo.result) {
            this.WXPay(this.payInfo, callbackurl);
        } else {
            //alert('支付授权错误');
            alert(this.payInfo.reason);//订单状态错误
            return false;
        }
    }
}

wxInterface.WXPay = function (obj, callbackurl) {
    //alert('进入支付');
    //appId:'wx22d352797b1b6b96',
    wx.chooseWXPay({
        timestamp: obj.timestamp,
        nonceStr: obj.nonceStr,
        package: 'prepay_id=' + obj.prepay_id,
        signType: 'MD5',//'SHA1', // 注意：新版支付接口使用 MD5 加密
        paySign: obj.sign,
        success: function (res) {
            alert('支付成功！');
            window.location.href = callbackurl;
        },
        cancel: function (res) {
            //alert(res);
            window.location.href = window.localStorage.getItem('locationUrl');
        },
        fail: function (res) {
            //alert(res);
            //window.location.reload(true);
            window.location.href = window.localStorage.getItem('locationUrl');
        }
    });
}

//预览图
wxInterface.splitPreviewImage = function (obj) {
    if (Object.prototype.toString.call(obj).indexOf('Array') != -1) {
        wxInterface.photoList.current = obj[0];
        wxInterface.photoList.urls = obj;
    }
}

//查看高清图像
wxInterface.splitPhoto = function (obj) {
    if (Object.prototype.toString.call(obj).indexOf('Array') != -1) {
        wxInterface.photo.current = obj[0];
        wxInterface.photo.urls = obj;
    }
}
wxInterface.previewImage = function (obj) {
    wx.previewImage({
        current: obj.current,
        urls: obj.urls
    });
}